Skip to content

feat(grid): add select/combo editor types for category products inline edit#157

Merged
biz87 merged 3 commits into
betafrom
feat/155-inline-edit-select-combo
Jun 21, 2026
Merged

feat(grid): add select/combo editor types for category products inline edit#157
biz87 merged 3 commits into
betafrom
feat/155-inline-edit-select-combo

Conversation

@Ibochkarev

@Ibochkarev Ibochkarev commented Mar 16, 2026

Copy link
Copy Markdown
Member

Описание

Добавлена поддержка select и combo для inline-редактирования в таблице товаров категории (closes #155). Базовая реализация расширяет PR #134; поверх первоначального коммита выполнен архитектурный рефакторинг (единый контракт опций, реестр справочников, composable).

Select (статические опции)

  • editor_type: 'select' в конфиге колонки
  • editor_options: [{ label, value }, ...]
  • Один PrimeVue Select с option-value="value" / option-label="label"

Combo (опции из API)

  • editor_type: 'combo'
  • editor_reference — ключ из серверного реестра (например vendors → путь к API)
  • editor_combo_endpoint (опционально) — переопределение URL только если путь в белом списке (префикс /api/mgr/references/)
  • Приоритет: валидный override → иначе URL из реестра по editor_reference. Должен быть задан reference или allowlisted endpoint (валидация при сохранении в GridFieldsConfig и на бэкенде)

API и контракт данных

  • GET .../references/vendors дополняет ответ массивом options: [{ value, label }]; поле vendors сохранено для обратной совместимости
  • Фронт после загрузки везде использует { value, label }[] (toSelectOptionsFromReferencesResponse)

Бэкенд

  • GridEditorReferenceRegistry — whitelist ключ → путь, проверка allowlist для override
  • GridColumnEditorType — константы типов редактора (text, number, select, combo)
  • GridConfigService — сохранение editor_reference, editor_combo_endpoint, очистка combo-полей при смене типа
  • GridConfigController — в ответе конфига для category-products передаётся editor_references для UI

Фронтенд (vueManager)

  • useCategoryProductsInlineEdit — состояние inline-edit, загрузка combo, сохранение
  • utils/gridEditorOptions.js — чистые функции: allowlist URL, резолв URL, маппинг ответа API → опции
  • constants/gridColumnEditorTypes.js — замороженный объект + normalizeGridColumnEditorType / хелперы
  • CategoryProductsGrid — подключение composable, один Select для select+combo
  • GridFieldsConfig — выбор reference, поле override URL, лексиконы ru/en

Тип изменений

  • Новая функциональность (non-breaking: старые конфиги с только editor_combo_endpoint продолжают работать как override)
  • Breaking change
  • Рефакторинг

Связанные Issues

Closes #155

Как протестировано

  • Ручное тестирование
  • ESLint (vueManager)
  • PHPStan (при наличии в CI)

Сценарии:

  • Колонка с editor_type: select и JSON editor_options
  • Combo с editor_reference: vendors без override
  • Combo с allowlisted editor_combo_endpoint
  • Ошибка при пустом combo без reference и без endpoint; toast при ошибке загрузки combo
  • showClear для nullable combo-полей

Чеклист

  • Лексиконы ru и en
  • CHANGELOG.md обновлён
  • Стиль проекта соблюдён

Дополнительно

  • ProductDataService::$allowedUpdateFields по-прежнему должен включать редактируемые поля (например vendor_id, made_in).

@Ibochkarev Ibochkarev marked this pull request as ready for review March 16, 2026 10:41
@Ibochkarev Ibochkarev requested a review from biz87 March 16, 2026 10:41
@Ibochkarev Ibochkarev force-pushed the feat/155-inline-edit-select-combo branch from e54131b to c534194 Compare April 19, 2026 05:05
@Ibochkarev Ibochkarev force-pushed the feat/155-inline-edit-select-combo branch from 2eee283 to 606cd06 Compare May 17, 2026 05:34
Registry, composable, options API; GridFieldsConfig editor types; CHANGELOG/lexicon.
@Ibochkarev Ibochkarev force-pushed the feat/155-inline-edit-select-combo branch from 606cd06 to 18a29eb Compare May 17, 2026 15:55
Three issues found during manual testing of category-products inline-edit:

1. Type mismatch in Select v-model vs editor_options
   PrimeVue Select uses strict (===) comparison between v-model and
   option-value. If editor_options stores values as numbers (1/0) but
   the row value comes as boolean (true/false from xPDO bool cast), no
   option matches and Select renders empty when opened on an existing row.
   Fix: coerceValueToOptionType() normalizes the raw row value to match
   the type of editor option values (bool↔int↔string) before assigning
   to inlineEditValue. Applied for both static select and async combo.

2. ESC does not dismiss Select editor
   Per-element @keydown.escape did not work for Select — PrimeVue Select
   captures Escape for its own dropdown handling. Document-level keydown
   listener now reliably cancels the editor regardless of focus.

3. No click-outside dismiss
   Active editor could only be dismissed by saving or activating another
   cell — no mouse way to abandon the edit. Document-level click listener
   added. Uses 'click' (not 'mousedown') so InputText/InputNumber @blur
   fires first and saves before our handler clears state. Skips clicks
   inside .inline-edit-cell and inside PrimeVue overlays
   (.p-select-overlay, .p-overlay, .p-component-overlay) so option clicks
   in the open dropdown are not misinterpreted as outside-clicks.

All three handlers live in useCategoryProductsInlineEdit composable; no
template or other consumer changes required. Listeners attach on composable
init and detach via onUnmounted.
@biz87

biz87 commented Jun 21, 2026

Copy link
Copy Markdown
Member

Прокликали на dev-стенде PR + наш follow-up патч (коммит d3f4c05):

Что работает:

  • ✅ Select после dblclick — показывает текущее значение, autosave через @change.
  • ✅ Combo — подгружает справочник через API (vendors reference), autosave.
  • ✅ Type coercion (coerceValueToOptionType) — Select подсвечивает правильную опцию, даже если editor_options.value (int) не совпадает по типу с raw row value (bool).
  • ✅ ESC закрывает редактор для всех типов (text, number, checkbox, select, combo).
  • ✅ Click-outside dismiss работает: для text/number — через @blur-save → state cleanup; для select/checkbox — primary dismiss. Click внутри dropdown overlay не считается outside.

Known issues (follow-up, не блокеры):

  • 🟡 Display formatter для editor_type=select/combo отсутствует. В ячейке отображается raw value (true/false вместо Yes/No, vendor_id=42 вместо «Acme Inc.»). Inline-edit работает корректно, отображение в режиме просмотра — нет. Открыт как отдельный issue / follow-up.

PHPStan чист по backend-файлам PR. mergeStateStatus CLEAN.

Мержим.

@biz87 biz87 merged commit 818fc26 into beta Jun 21, 2026
@biz87 biz87 deleted the feat/155-inline-edit-select-combo branch June 21, 2026 13:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: inline edit — select/combo editor type for category products grid

3 participants